package com.situ.gym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.situ.gym.pojo.Permission;
import com.situ.gym.mapper.PermissionMapper;
import com.situ.gym.pojo.vo.PermissionVO;
import com.situ.gym.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gao
 * @since 2025-09-01
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //1.使用Map实现缓存
    //缺点：1、在内存中，重启就销毁 2、只能在单机模式下面有效，无法实现分布式环境缓存
    private Map<String, Object> map = new HashMap<String, Object>();

    @Override
    public void update(Permission permission) {
        permissionMapper.updateById(permission);
        //修改数据库，删除缓存
        redisTemplate.delete("permissionVOTree");
    }

    @Override
    public List<PermissionVO> selectPermissionTree() {
        //1.先检查redis缓存中有没有数据
        List<PermissionVO> permissionVOTree = redisTemplate.opsForList().range("permissionVOTree", 0, -1);
        //2.redis缓存里面如果没有数据
        if (CollectionUtils.isEmpty(permissionVOTree)) {
            //3.查询数据库
            //查找所有权限
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("sort");
            List<Permission> permissionList = permissionMapper.selectList(queryWrapper);

            List<PermissionVO> permissionVOList = new ArrayList<>();
            permissionList.forEach(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                permissionVOList.add(permissionVO);
            });

            permissionVOTree = buildTree(permissionVOList);

            //4.更新到reids缓存中
            redisTemplate.opsForList().rightPushAll("permissionVOTree", permissionVOTree);
        }

        return permissionVOTree;
    }


    //@Override
    public List<PermissionVO> selectPermissionTree1() {
        //1.先检查map缓存中有没有数据
        List<PermissionVO> permissionVOTree = (List<PermissionVO>) map.get("permissionVOTree");
        //2.map缓存里面如果没有数据
        if (CollectionUtils.isEmpty(permissionVOTree)) {
            //3.查询数据库
            //查找所有权限
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("sort");
            List<Permission> permissionList = permissionMapper.selectList(queryWrapper);

            List<PermissionVO> permissionVOList = new ArrayList<>();
            permissionList.forEach(permission -> {
                PermissionVO permissionVO = new PermissionVO();
                BeanUtils.copyProperties(permission, permissionVO);
                permissionVOList.add(permissionVO);
            });

            permissionVOTree = buildTree(permissionVOList);

            //4.更新到map缓存中
            map.put("permissionVOTree", permissionVOTree);
        }

        return permissionVOTree;
    }




    @Override
    public List<PermissionVO> selectRouterTreeByAdminId(Integer id) {
        //1.查找当前用户的所有权限
        List<Permission> permissionList = permissionMapper.selectPermissionByAdminId(id);
        //2.将List<Permission> 转换成List<PermissionVO>
        List<PermissionVO> permissionVOList = new ArrayList<>();
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });
        //3.构建树形结构
        List<PermissionVO> permissionVOTree = buildTree(permissionVOList);
        //4.只保留路由
        //List<RouterVO> routerTreeList = buildRouterTree(permissionVOTree);
        return permissionVOTree;
    }

    /*private List<RouterVO> buildRouterTree(List<PermissionVO> permissionVOTree) {
        List<RouterVO> routerTreeList = new ArrayList<>();
        //首先遍历一级目录
        for (PermissionVO permissionVO : permissionVOTree) {
            RouterVO routerVO = new RouterVO();

        }
    }*/

    @Override
    public List<String> selectBtnListByAdminId(Integer id) {
        List<Permission> permissionList = permissionMapper.selectPermissionByAdminId(id);
        List<String> btnList = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getType() == 2) {
                btnList.add(permission.getPermissionValue());
            }
        }
        return btnList;
    }

    @Override
    public List<PermissionVO> selectRouterTreeByUserId(Integer id) {
        //1.查找当前用户的所有权限
        List<Permission> permissionList = permissionMapper.selectPermissionByUserId(id);
        //2.将List<Permission> 转换成List<PermissionVO>
        List<PermissionVO> permissionVOList = new ArrayList<>();
        permissionList.forEach(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            permissionVOList.add(permissionVO);
        });
        //3.构建树形结构
        List<PermissionVO> permissionVOTree = buildTree(permissionVOList);
        //4.只保留路由
        //List<RouterVO> routerTreeList = buildRouterTree(permissionVOTree);
        return permissionVOTree;
    }

    @Override
    public List<String> selectBtnListByUserId(Integer id) {
        List<Permission> permissionList = permissionMapper.selectPermissionByUserId(id);
        List<String> btnList = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getType() == 2) {
                btnList.add(permission.getPermissionValue());
            }
        }
        return btnList;
    }



    private List<PermissionVO> buildTree(List<PermissionVO> permissionVOList) {
        List<PermissionVO> treeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permissionVO : permissionVOList) {
                if (permissionVO.getParentId() == 0) {
                    permissionVO.setChildren(buildChildTree(permissionVO, permissionVOList));
                    treeList.add(permissionVO);
                }
            }
        }

        return treeList;
    }

    /**
     *
     * @param permissionVO  要查找的孩子的父亲
     * @param permissionVOList 所有分类的集合
     * @return
     */
    private List<PermissionVO> buildChildTree(PermissionVO permissionVO, List<PermissionVO> permissionVOList) {
        List<PermissionVO> childTree = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionVOList)) {
            for (PermissionVO permission : permissionVOList) {
                if (permission.getParentId().longValue() == permissionVO.getId().longValue()) {
                    //添加孩子的时候，首先把这个孩子的孩子的集合查出来
                    permission.setChildren(buildChildTree(permission, permissionVOList));
                    childTree.add(permission);
                }
            }
        }
        return childTree;
    }
}
